package com.jsz.peini.redis.base;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Han Guohong
 * @version 2017-3-1 下午5:26:36 
 * 序列化工具类
 */
public class SerializeUtil {
	private static final Logger logger = LoggerFactory.getLogger(SerializeUtil.class);
	/**
	 * 将list序列化
	 * @author Han Guohong
	 * @param list
	 * @return
	 * @throws IOException 
	 */
	public static byte[] serialize(List<Object> list){
		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;
		try {
			// 序列化
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			for (Object obj : list) {
				oos.writeObject(obj);
			}
			oos.writeObject(null);
			byte[] bytes = baos.toByteArray();
			
			oos.close();
			baos.close();
			return bytes;
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			try {
				oos.close();
				baos.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 将对象序列化
	 * @author Han Guohong
	 * @param object
	 * @return
	 * @throws IOException 
	 */
	public static byte[] serialize(Object object) {
		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;
		try {
			// 序列化
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			byte[] bytes = baos.toByteArray();
			
			oos.close();
			baos.close();
			return bytes;
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			try {
				oos.close();
				baos.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 反序列化
	 * @author Han Guohong
	 * @param bytes
	 * @return
	 * @throws IOException 
	 */
	public static Object unserialize(byte[] bytes){
		ByteArrayInputStream bais = null;
		ObjectInputStream ois = null;
		try {
			// 反序列化
			bais = new ByteArrayInputStream(bytes);
			ois = new ObjectInputStream(bais);
			
			ois.close();
			bais.close();
			return ois.readObject();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			try {
				ois.close();
				bais.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}
}
